package com.dhgate.spu.analysis.index;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhgate.spu.analysis.bean.Product;
import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.util.StringUtil;

/** 
 * @author:      wangguodong 
 * @create:      2014-2-14 下午6:44:45 
 * @description: 
 */
public class SolrClient {
	private static final Logger logger = LoggerFactory.getLogger(SolrClient.class);
//	
//	<dynamicField name="*_type" type="string"          indexed="true" stored="true" /><!-- 类型 比如品牌类型、ram类型 是否为提取 -->
//    <dynamicField name="*_num"  type="int"             indexed="true" stored="true" /> <!-- 统计信息，比如提前出来几个品牌 -->
//    <dynamicField name="spu_*"  type="string"          indexed="true" stored="true" /><!-- spu的主键，比如spu规则1 brand_ram_model 规则2 brand_screen.. -->
//    <dynamicField name="is_*
	public static void index(List<Product> products){
		int count = 0;
		List<SolrInputDocument> docList = new ArrayList<SolrInputDocument>();
		SolrInputDocument doc;
		for(Product p: products){
			doc = new SolrInputDocument();
			doc.addField("indexnumber", p.getIndexNumber());
			doc.addField("itemcode", p.getItemCode());
			doc.addField("productname", p.getProductName());
			doc.addField("prodlineid", p.getProdLineId());
			doc.addField("supplierid", p.getSupplierid());
			doc.addField("spushortdescription", p.getShortDescription()+"-");
			doc.addField("spukeywords", p.getKeywords()+"-");
			//抽取ext字段
			addField(doc,p.getExtFieldMap());
			//原始字段
			addField(doc,p.getFieldMap());
			
			docList.add(doc);
			count++;
			if(count%SysConsts.SOLR_BATCH_ADD_SIZE == 0){
				send2Solr(docList);
				docList = new ArrayList<SolrInputDocument>();
			}
		}
		
		if(docList.size() > 0){
			send2Solr(docList);
		}
	}
	
	private static void addField(SolrInputDocument doc, Map<String,String> fieldMap){
		if(fieldMap == null || fieldMap.size() == 0){
			return ;
		}
		
		Iterator<Map.Entry<String, String>> it = fieldMap.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = it.next();
			doc.addField(entry.getKey(), entry.getValue());
		}
		
	}
	private static String getFieldValue(Product p, String fieldName){
		if(StringUtil.isNotEmpty(p.getField(fieldName))){
			return p.getField(fieldName);
		}
		return p.getExtField(fieldName);
	}
	private static void send2Solr(List<SolrInputDocument> docList)  {
		try {
			SysConsts.SOLR_SERVER.add(docList);
			logger.debug("send solr "+docList.size()+" docs");
		} catch (Exception e) {
			logger.error("send2Solr error:"+e);
			e.printStackTrace();
		}
	}

}
